package cmu.mobile.lab;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;

public class MMSObserver extends ContentObserver {
	
	ContentResolver contentResolver;
	
	public MMSObserver(Handler handler, ContentResolver cr) {
		super(handler);
		contentResolver = cr;
	}
	
	@Override
	public void onChange (boolean arg0) {
		super.onChange(arg0);
		
		Cursor curPdu = contentResolver.query(Uri.parse("content://mms/"),
				null, null, null, null);
		if (curPdu.moveToNext()) {
			String id = curPdu.getString(curPdu.getColumnIndex("_id"));
		//	String thread_id = curPdu.getString(curPdu
		//			.getColumnIndex("thread_id"));
		//	String subject = curPdu.getString(curPdu.getColumnIndex("sub"));
		//	String date = curPdu.getString(curPdu.getColumnIndex("date"));
			
		//	String selectionAddr = "msg_id = '" + id + "'";
			Cursor curAddr = contentResolver.query(Uri.parse("content://mms/" 
					+ id + "/addr"), null, null, null, null);
			if (curAddr.moveToNext()) {
			//	String contact_id = curAddr.getString (curAddr
			//			.getColumnIndex ("contact_id"));
			//	String address = curAddr.getString (curAddr
			//			.getColumnIndex ("address"));
			//	String selectionPart = new String ("mid = '" + id + "'");
				Cursor curPart = contentResolver.query(Uri
						.parse("content://mms/part"), null, null, null, null);
				
				String values[] = null;
				while (curPart.moveToNext()) {
					String[] columns = curPart.getColumnNames();
					if (values == null)
						values = new String[columns.length];
					for (int i = 0; i < curPart.getColumnCount(); i++) {
						values[i] = curPart.getString(i);
					}
					
				//	String contact_idd = curPart.getString(0);
					
					if (values[3].equals("image/jpeg")) {
						GetMmsAttachment(values[0], values[12], values[4]);
					}
				}
			}
			
		}
		
		MMSContent mms = new MMSContent();
		
		
	}
	
	private void GetMmsAttachment(String _id, String _data, String filename) {
		Uri partURI = Uri.parse("content://mms/part/" + _id);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		InputStream is = null;
		
		try {
			is = contentResolver.openInputStream(partURI);
			byte[] buffer = new byte[256];
			int len = is.read(buffer);
			while (len >= 0) {
				baos.write(buffer, 0, len);
				len = is.read(buffer);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				ByteArrayInputStream bais = new ByteArrayInputStream(
						baos.toByteArray());
				try {
					is.close();
					bais.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		
	}

}
